<template>
 <div class="InstitutionManage-wrapper">
   <!-- 左侧树形结构 -->
   <div class="left-content">
    <h2>组织机构</h2>
     <div>
      <a-input-search style="margin-bottom: 8px" placeholder="请输入关键字" @change="onChange" class="leftSearchInput" />
      <a-tree
        :auto-expand-parent="true"
        :tree-data="realgData"
        :replaceFields = "{children:'child', title:'name', key:'id'}"
        @select="chooseTreeNode"
      >
        <template slot="title" slot-scope="{ title }">
          <span v-if="title.indexOf(searchValue) > -1">
            {{ title.substr(0, title.indexOf(searchValue)) }}
            <span style="color: #f50">{{ searchValue }}</span>
            {{ title.substr(title.indexOf(searchValue) + searchValue.length) }}
          </span>
          <span v-else>{{ title }}</span>
        </template>
      </a-tree>
    </div>
   </div>
   <!-- 右侧展示结构 -->
   <div class="right-content">
     <!-- 头部搜索区域 -->
     <div class="search-wrapper">
       <!-- 头部搜索 -->
       <a-form-model :model="searchFormData" :label-col="labelCol" :wrapper-col="wrapperCol" ref="searchFormRef">
          <a-form-model-item label="组织名称:" class="serach-input">
            <a-input placeholder = "模糊搜索组织名称" size = "large" v-model="searchFormData.name"/>
          </a-form-model-item>
       </a-form-model>
       <!-- 按钮组 -->
       <div class="btn-group">
         <a-button type="success" icon="search" @click="searchBtnClick" style="background-color:#0079FE;color:#fff">
          查询
        </a-button>
        <a-button @click="resetBtnClick">重置</a-button>
       </div>
     </div>
     <!-- 底部新增按钮和表格 -->
     <div class="table-area">
       <a-button type="primary" icon="plus" class="plus-btn" @click="addBtn" style="background-color:#0079FE;color:#fff">新增</a-button>
       <!-- <button  class="plus-btn" @click="addBtn">新增11</button> -->
       <!-- 表格 -->
       <a-table :columns="columns" :data-source="tableData" rowKey = "id">
          <!-- <a slot="name" slot-scope="text">{{ text }}</a>
          <span slot="customTitle"><a-icon type="smile-o" /> Name</span>
          <span slot="tags" slot-scope="tags">
            <a-tag
              v-for="tag in tags"
              :key="tag"
              :color="tag === 'loser' ? 'volcano' : tag.length > 5 ? 'geekblue' : 'green'"
            >
              {{ tag.toUpperCase() }}
            </a-tag>
          </span> -->
          <span slot="action" slot-scope="text">
          <!-- <span slot="action"> -->
            <a @click="editItem(text)">编辑</a>
            <a-divider type="vertical" />
            <a @click="disabledItem(text)">{{text.shield == 0? "禁用":"启用"}}</a>
          </span>
        </a-table>
     </div>
   </div>

   <!-- 表格数据编辑对话框 -->
  <a-modal
      title="新增/修改"
      :visible="editDialogVisible"
      :confirm-loading="confirmLoading"
      @ok="editDialogHandleOk"
      @cancel="editDialogHandleCancel"
    >
    <a-form-model ref = "editFormRef"  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" :model="editDialogFormData" :rules = "editDialogFormRules">
      <a-form-model-item label="名称" prop = "name">
        <a-input  v-model="editDialogFormData.name"/>
      </a-form-model-item>
      <a-form-model-item label="部门类型">
        <a-radio-group   v-model="editDialogFormData.type">
          <a-radio value="ENTERPRISE">
            企业
          </a-radio>
          <a-radio value="DEP">
            部门
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="组织编码" prop = "code">
        <a-input placeholder = "字母和数字组合" v-model="editDialogFormData.code"></a-input>
      </a-form-model-item>
      <a-form-model-item label="组织描述">
        <a-input  v-model="editDialogFormData.orgDesc"></a-input>
      </a-form-model-item>
      <a-form-model-item label="部门负责人">
        <a-input   v-model="editDialogFormData.principalUserId"></a-input>
      </a-form-model-item>
      <a-form-model-item label="上级分管领导">
        <a-input v-model="editDialogFormData.partLeaderUserId"></a-input>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
  <!-- 新增数据对话框 -->
  <a-modal
      title="新增/修改"
      :visible="addDialogVisible"
      :confirm-loading="confirmLoading"
      @ok="addDialogHandleOk"
      @cancel="addDialogHandleCancel"
    >
    <a-form-model ref = "addFormRef"  :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }" :model="addDialogFormData" :rules = "addDialogFormRules">
      <a-form-model-item label="名称" prop = "name">
        <a-input  v-model="addDialogFormData.name"/>
      </a-form-model-item>
      <a-form-model-item label="部门类型">
        <a-radio-group   v-model="addDialogFormData.type">
          <a-radio value="ENTERPRISE">
            企业
          </a-radio>
          <a-radio value="DEP">
            部门
          </a-radio>
        </a-radio-group>
      </a-form-model-item>
      <a-form-model-item label="组织编码" prop = "code">
        <a-input placeholder = "字母和数字组合" v-model="addDialogFormData.code"></a-input>
      </a-form-model-item>
      <a-form-model-item label="组织描述">
        <a-input  v-model="addDialogFormData.orgDesc"></a-input>
      </a-form-model-item>
      <a-form-model-item label="部门负责人">
        <a-input   v-model="addDialogFormData.principalUserId"></a-input>
      </a-form-model-item>
      <a-form-model-item label="上级分管领导">
        <a-input v-model="addDialogFormData.partLeaderUserId"></a-input>
      </a-form-model-item>
    </a-form-model>
  </a-modal>
 </div>
</template>

<script>
// 表格数据源
const data = [
  {
    key: '1',
    name: 'John Brown',
    age: 32,
    address: 'New York No. 1 Lake Park',
    tags: ['nice', 'developer'],
  },
  {
    key: '2',
    name: 'Jim Green',
    age: 42,
    address: 'London No. 1 Lake Park',
    tags: ['loser'],
  },
  {
    key: '3',
    name: 'Joe Black',
    age: 32,
    address: 'Sidney No. 1 Lake Park',
    tags: ['cool', 'teacher'],
  },
];
// 表格头部初始化数据
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    customRender: (text,record,index) => `${index+1}`,
  },
  {
    dataIndex: 'name',
    key: 'name',
    // slots: { title: 'customTitle' },
    // scopedSlots: { customRender: 'name' },
    title:"组织名称"
  },
  {
    title: '组织编号',
    dataIndex: 'code',
    key: 'code',
  },
  {
    title: '人数',
    dataIndex: 'userNumber',
    key: 'userNumber',
  },
  {
    title: '创建时间',
    key: 'createTime',
    dataIndex: 'createTime',
  },
  {
    title: 'Action',
    key: 'action',
    scopedSlots: { customRender: 'action' },
  },
];
// 树形结构初始化数据
  const x = 3;
  const y = 2;
  const z = 1;
  const gData = [];

  const generateData = (_level, _preKey, _tns) => {
    const preKey = _preKey || '0';
    const tns = _tns || gData;

    const children = [];
    for (let i = 0; i < x; i++) {
      const key = `${preKey}-${i}`;
      tns.push({ title: key, key, scopedSlots: { title: 'title' } });
      if (i < y) {
        children.push(key);
      }
    }
    if (_level < 0) {
      return tns;
    }
    const level = _level - 1;
    children.forEach((key, index) => {
      tns[index].children = [];
      return generateData(level, key, tns[index].children);
    });
  };
  generateData(z);

  const dataList = [];
  const generateList = data => {
    for (let i = 0; i < data.length; i++) {
      const node = data[i];
      const key = node.key;
      dataList.push({ key, title: key });
      if (node.children) {
        generateList(node.children);
      }
    }
  };
  generateList(gData);

  const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
      const node = tree[i];
      if (node.children) {
        if (node.children.some(item => item.key === key)) {
          parentKey = node.key;
        } else if (getParentKey(key, node.children)) {
          parentKey = getParentKey(key, node.children);
        }
      }
    }
    return parentKey;
  };

  import { InstitutionManageTreeData ,InstitutionManageListData,InstitutionManageListDataPOST,InstitutionManageListDataDisabled,InstitutionManageListDataAdd} from '@/services/user.js'
 export default {
  name: '',
  data () {
   return {
      expandedKeys: [],
      searchValue: '',
      autoExpandParent: true,
      gData,
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      data,
      columns,
      realgData:[],
      // 点击树状图节点,获取父级部门id
      pid:"",
      // 搜索表单数据
      searchFormData:{
        name:""
      },
      // 表格数据
      tableData:[],
      // 编辑对话框显示隐藏
      editDialogVisible:false,
      // 新增对话框显示隐藏
      addDialogVisible:false,
      // 编辑对话框确认按钮状态
      // 新增对话框确认按钮状态
      confirmLoading:false,
      // 编辑对话框表格数据收集
      editDialogFormData:{
        name:"",
        type:"",
        code:"",
        parentId:"",
        orgDesc:"",
        // 部门负责人id
        principalUserId:"",
        // 上级分管领导用户id
        partLeaderUserId:""
      },
      // 新增对话框表格数据收集
      addDialogFormData:{
        name:"",
        type:"",
        code:"",
        parentId:"",
        orgDesc:"",
        // 部门负责人id
        principalUserId:"",
        // 上级分管领导用户id
        partLeaderUserId:""
      },
      // 编辑对话框校验规则
      editDialogFormRules:{
        name:[{ required: true, message: '请输入组织名称', trigger: 'blur' }],
        code:[{ required: true, message: '请输入组织编码', trigger: 'blur' }]
      },
      // 新增对话框校验规则
      addDialogFormRules:{
        name:[{ required: true, message: '请输入组织名称', trigger: 'blur' }],
        code:[{ required: true, message: '请输入组织编码', trigger: 'blur' }]
      },
      // 当前修改行的id  修改请求需要携带此id
      putId:''
   }
  },
  created() {
    // 请求树状图数据
    this.InstitutionManageTreeData()
  },
  methods: {
    // 搜索表单搜索按钮事件函数
    searchBtnClick(){
      console.log(this.searchFormData);
      // TODO 里面需要传pid和部门名称
      InstitutionManageListData().then(res => {this.tableData = res.data.data.rows;})
    },
    // 搜索表单重置按钮事件函数
    resetBtnClick(){
      // 重置表单没有作用
      this.$refs.searchFormRef.resetFields();
    },
    // 新增按钮响应函数
    addBtn(){
      this.addDialogVisible = true
    },
    // 编辑对话框取消按钮响应函数
    editDialogHandleCancel(){
      // TODO 取消按钮点击 重置对话框 表单数据
      console.log('点击取消');
      // this.$refs.editFormRef.resetFields()
      this.editDialogVisible = false
    },
    // 新增对话框取消按钮响应函数
    // TODO 新增操作结束之后需要刷新table列表
    addDialogHandleCancel(){
      // TODO 取消按钮点击 重置对话框 表单数据
      console.log('点击取消');
      // this.$refs.editFormRef.resetFields()
      this.addDialogVisible = false
    },
    // 编辑对话框确认按钮响应函数
    // TODO编辑操作结束之后需要刷新table列表
    editDialogHandleOk(){
      // TODO 收集数据 发送网络请求 成功之后 取消确认按钮加载状态 隐藏对话框
      // 校验规则没问题才发送网络请求
      console.log(111);
      InstitutionManageListDataPOST(this.putId,this.editDialogFormData).then(res => {
            // TODO 如果成功,取消加载状态,关闭对话框
            // if(res.data.status == 0){
            //   this.confirmLoading = false
            //   this.editDialogVisible = false
            // }
            console.log(res);
      })
      // this.$refs.editFormRef.validate(valid => {
      //   this.confirmLoading = true
      //   console.log(valid);
      //   if(valid){

      //   }else{
      //     console.log('确认按钮失败');
      //   }
      // })
    },
    // 新增对话框确认按钮响应函数
    addDialogHandleOk(){
      // TODO 收集数据 发送网络请求 成功之后 取消确认按钮加载状态 隐藏对话框
      // 校验规则没问题才发送网络请求
      this.addDialogFormData.parentId = this.pid
      // 发送新增请求
      InstitutionManageListDataAdd(this.addDialogFormData).then(res => {
        console.log(res);
        this.addDialogVisible = false
      })
      console.log('新增')
    },
    // 表格数据编辑响应函数
    editItem(text){
      // 显示编辑对话框
      // 显示对话框的同时把数据带过去
      this.editDialogVisible = true
      this.editDialogFormData.name = text.name
      this.editDialogFormData.code = text.code
      this.putId = text.id
      // 目前假数据 先不带tyoe
      // this.editDialogFormData.type = text.type
      console.log('edit');
    },
    // 表格数据禁用响应函数
    disabledItem(text){
      console.log(text);
      // 状态切换
      text.shield =  text.shield== 0 ? 1:0
      // 发送网络请求
      InstitutionManageListDataDisabled(text.id,text.shield).then(res => {
        console.log(res);
      })
    },
    // 点击树状图选择,并且发送网络请求,根据id查询部门分页列表
    chooseTreeNode(selectedKeys){
      // pid存起来了
      this.pid = selectedKeys[0]
      console.log(this.pid);
      InstitutionManageListData(this.pid,1,10).then(res => {this.tableData = res.data.data.rows;console.log(this.tableData);})
    },
    // 左侧树状图数据请求
    InstitutionManageTreeData(){
      InstitutionManageTreeData().then(res => {
        console.log(res);
        this.realgData = res.data.data
      })
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    onChange(e) {
      const value = e.target.value;
      const expandedKeys = dataList
        .map(item => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, gData);
          }
          return null;
        })
        .filter((item, i, self) => item && self.indexOf(item) === i);
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      });
    },
  },
  components: {

  }
 }
</script>

<style lang="less" scoped>
.InstitutionManage-wrapper{
  padding: 40px 0 0 0;
}
  .left-content{
    float: left;
    width: 20%;
    border: 1px solid #bebdbd;
    border-radius: 6px;
    // padding: 10px;
    overflow: hidden;
    h2{
      height: 49px;
      line-height: 49px;
      background-color: #F5F5F5;
      border-radius: 6px;
      font-size: 14px;
      padding: 3px 0 0 10px;
      font-weight: bold;
    }
    .leftSearchInput{
      width: 70%;
      margin-left: 30px;
      margin-top: 10px;
    }
  }
  .right-content{
    float: left;
    width: 70%;
    // border: 1px solid #999;
    padding-left: 20px;
    .search-wrapper{
      position: relative;
      width: 100%;
      height: 100px;
      border: 1px solid #bebdbd;
      border-radius: 3px;
      padding: 20px 40px;
      .serach-input{
        width: 400px;
        input{
          margin-left: 10px;
        }
      }
      .btn-group{
        position: absolute;
        right: 40px;
        top: 20px;
        button{
          margin-right: 40px;
          width: 80px;
          height: 40px;
        }
      }
    }
    .table-area{
      padding: 55px 0;
      position: relative;
      .plus-btn{
        position: absolute;
        right: 0;
        top: 10px;
        z-index: 99;
        margin-bottom: 10px;
        width: 80px;
        height: 40px;
      }
    }
  }
 
</style>
